<template>
  <div class="energy" :class="{ 'show-more-open': showMore }">
    <div class="energy-title">
      <div class="nav-left">
        <img class="company-logo" src="../../../styles/logo.svg" alt="" />
        <span class="title">能耗管理</span>
      </div>
      <div class="nav-center">
        <!-- <iconSvg
          name="filter"
          w="20px"
          h="22px"
          @click.native="changeMore"
        ></iconSvg> -->
        <!-- <iconSvg name="g6change" w="25" style="color:#fff;margin-left: 8px;" @click.native="backToG6page('g6')"></iconSvg> -->
      </div>
      <div class="nav-right">
        <iconSvg
          name="home"
          w="20px"
          h="22px"
          class="right_icon"
          @click.native="backToHomepage"
        ></iconSvg>
      </div>
    </div>
    <Application></Application>
    <div class="energy-work">
      <tab
        class="energy-tab"
        style="z-index:0"
        active-color="#456de6"
        default-color="#fff"
        custom-bar-width="80%"
      >
        <tab-item
          v-for="item in deviceEnergyType"
          :key="item.key"
          @on-item-click="handler(item)"
          :selected="type == item.code"
        >
          {{ item.name }}
        </tab-item>
      </tab>
      <div class="energy-work-wrapper">
        <div class="chart-box">
          <!-- <chart-list :chart-list="chartList"></chart-list> -->
          <div class="chart-title">
            <span>
              用量
            </span>
            <div class="group-list">
              <span
                class="list-item"
                :class="{ active: chartActive === index + 1 }"
                @click="changeWidgetIndex(index + 1)"
                v-for="(item, index) in ['日', '月', '年']"
                :key="index"
              >
                {{ item }}
              </span>
            </div>
          </div>

          <div class="chart-area" id="chart" ref="chart"></div>
        </div>
        <!-- <mescroll-vue :up="mescrollUp" @init="mescrollInit"> -->
        <iu-card
          class="energy-card"
          @click.native="energyDetails(item, index)"
          v-for="(item, index) in tableData"
          :key="index"
          :tipType="/异常/.test(item.deviceRunStatus) ? 'error' : ''"
        >
          <template #title>
            {{ item.departmentName }} - {{ item.deviceName }}
          </template>
          <template #tip>
            {{ item.deviceRunStatus }}
          </template>
          <template #body>
            <div class="energy-card-body">
              <div class="body-item">
                <span class="body-item-key">总用量</span>
                <span class="body-item-value">{{ item.curMeterValue }}</span>
              </div>
              <div class="body-item">
                <span class="body-item-key">用量：</span>
                <span
                  class="body-item-value"
                  :class="{
                    warning: /异常/.test(item.deviceRunStatus)
                  }"
                  >{{ item.useValue }}</span
                >
              </div>
              <div class="body-item">
                <span class="body-item-key">表盘读数：</span>
                <span class="body-item-value">{{ item.dialValue }}</span>
              </div>
              <div class="body-item">
                <span class="body-item-key">倍率：</span>
                <span class="body-item-value">{{ item.magnification }}</span>
              </div>
              <div class="body-item">
                <span class="body-item-key">采集时间：</span>
                <span class="body-item-value">
                  {{ item.dataTime | formatDate }}
                </span>
              </div>
              <div class="body-item">
                <span class="body-item-key">数据类型：</span>
                <span class="body-item-value">
                  {{ item.dataSource ? "其他" : "仪表" }}
                </span>
              </div>
            </div>
          </template>
        </iu-card>
        <div class="newpage_work_more" v-if="showMoreBtn" @click="getMore">
          查看更多
        </div>
        <!-- </mescroll-vue> -->
      </div>
    </div>
    <transition name="fade">
      <div
        v-show="showMore"
        class="MoreDataP"
        ref="MoreDataP"
        @click.self="showMore = false"
      >
        <div class="nav-center">
          筛选
        </div>
        <div class="MoreDataPInner">
          <div class="searchItem">
            <div class="title">部门</div>
            <div class="inner">
              <div class="curSelectItem">
                <div class="department_box">
                  <div
                    class="department_select"
                    :class="showTree ? 'active' : ''"
                    @click="showTreeFn(true)"
                  >
                    <p class="department_name">
                      {{ curDepartment.departmentName }}
                    </p>
                    <iconSvg
                      name="downFill"
                      w="23px"
                      height="13px"
                      class="selece_icon"
                      ref="selece_icon"
                    ></iconSvg>
                  </div>
                  <transition name="slide">
                    <div class="dep_box" v-show="showTree">
                      <dep-tree
                        @changeId="change"
                        @showTreeFn="showTreeFn"
                        :initDepartment="curDepartment"
                      ></dep-tree>
                    </div>
                  </transition>
                </div>
              </div>
            </div>
            <div class="title">数据名称</div>
            <div class="inner">
              <input
                type="text"
                placeholder="请输入"
                v-model.trim="search.deviceName"
                :max="20"
              />
            </div>
            <div class="title">采集时间</div>
            <div class="inner">
              <div class="time">
                <div class="time-span" @click="selectTime(0)">
                  {{ search.startTime || "&nbsp;" }}
                </div>
                <div class="time-text">至</div>
                <div class="time-span" @click="selectTime(1)">
                  {{ search.endTime || "&nbsp;" }}
                </div>
              </div>
            </div>
          </div>
        </div>
        <div class="BtnGroup">
          <div class="btn-reset" @click="reset">
            重置
          </div>
          <div class="btn-over" @click="overBtn">
            确认
          </div>
        </div>
      </div>
    </transition>
  </div>
</template>
<script>
import { Tab, TabItem, TransferDom } from "vux";
import MescrollVue from "mescroll.js/mescroll.vue";
import iuCard from "@/components/common/card/index";
import Application from "@/components/common/application";

import EnergyConsumeDao from "@/daos/energy_consume";

import depTree from "@/components/common/tree";
import dayjs from "dayjs";

import ChartList from "@/components/common/chart_list/index";
import DataAnalysisDao from "@/daos/data_analysis_dao";

export default {
  name: "energyConsume",
  directives: {
    TransferDom
  },
  components: {
    Tab,
    TabItem,
    MescrollVue,
    depTree,
    ChartList,
    Application,
    iuCard
  },
  data() {
    return {
      type: "",
      chartActive: 0,
      showMore: false,
      showMoreBtn: false,
      tableData: [],
      waterData: [],
      electricityData: [],
      chartList: [],
      certificateAuth: false,
      showTree: false,
      mescroll: null,
      chart: null,
      chartData: [],
      curDepartment: {
        departmentName: "全企业",
        id: "0"
      },
      deviceEnergyType: [],
      deviceEnergyTypeAction: "Electricity",
      mescrollUp: {
        callback: this.getMore,
        page: {
          num: 0,
          size: 10
        },
        htmlNodata: '<p class="upwarp-nodata">-- 暂无更多的数据 --</p>',
        noMoreSize: 5,
        toTop: {
          src: "./static/mescroll-totop.png",
          offset: 1000
        },
        isBounce: false
      },
      pageSize: 10,
      pageNum: 1,
      demo01: "",
      search: {
        departmentId: "",
        deviceName: "",
        deviceCode: "",
        startTime: "",
        endTime: ""
      },
      list: [
        { key: "gd", value: "广东" },
        { key: "gx", value: "广西" }
      ],
      total: 0,
      store: {
        pageNum: 0,
        id: 0
      }
    };
  },
  //返回首页的公共方法
  inject: ["backToHomepage",'backToG6page'],
  activated() {
    this.init();
  },
  mounted() {
    this.curDepartment = {
      departmentName: "全企业",
      id: ""
    };
    // this.getChartConfig();
  },
  computed: {
    user() {
      if (!this.$store.state.user) {
        this.$store.commit(
          "saveUser",
          JSON.parse(localStorage.getItem("user"))
        );
      }
      return this.$store.state.user;
    }
  },
  methods: {
    init() {
      if (!this.deviceEnergyType.length) {
        this.getDictionary();
      } else {
        this.getEnergyConsumeMore();
        this.changeWidgetIndex(2);
      }
    },
    mescrollInit(mescroll) {
      this.mescroll = mescroll;
    },
    handler(e) {
      this.pageNum = 1;
      // this.pageSize = 5;
      this.type = e.code;
      // this.deviceEnergyTypeAction = e.key;
      this.reset();
      this.store.pageNum = 0;
      this.getEnergyConsumeMore(null);
      this.changeWidgetIndex(2);
    },
    getChartConfig() {
      let params = {
        code: "SJ02",
        departmentId: this.curDepartment.id || this.user.department.id
      };
      DataAnalysisDao.getChartConfig(params, res => {
        this.chartList.splice(0);
        if (res && res.length) {
          this.chartList = res.map(e => {
            e.show = 0;
            e.code = "SJ02";
            return e;
          });
        }
      });
    },
    getMore(page, mescroll) {
      // this.pageNum = page.num;
      this.store.pageNum = 0;
      this.pageNum++;
      this.getEnergyConsumeMore();
    },
    getDictionary() {
      EnergyConsumeDao.energyDictionary(data => {
        if (data && data.childs.length) {
          this.deviceEnergyType.splice(0);
          this.deviceEnergyType = data.childs;
          if (this.deviceEnergyType[0]) {
            this.$nextTick(e => {
              this.handler(this.deviceEnergyType[0]);
            });
          }
        }
      });
    },
    getEnergyConsumeMore() {
      let params = {
        orgId: this.user.org.id,
        pageSize: this.pageSize,
        pageNum: this.store.pageNum || this.pageNum,
        departmentId: this.curDepartment.id,
        deviceName: this.search.deviceName,
        startTime: this.search.startTime,
        endTime: this.search.endTime,
        type: this.type
      };

      EnergyConsumeDao.getEnergyConsumeRecordList(params, res => {
        // EnergyConsumeDao[`getEnergyConsume${this.deviceEnergyTypeAction}`](params, res => {
        if (this.pageNum === 1) {
          this.tableData.splice(0);
        }
        if (res.content && res.content.length) {
          this.tableData.splice(
            ((this.store.pageNum || this.pageNum) - 1) * this.pageSize,
            this.pageSize,
            ...res.content
          );
        }

        this.showMoreBtn = this.pageNum * this.pageSize < +res.total;
      });
    },
    selectTime(index) {
      let _this = this;
      this.$vux.datetime.show({
        cancelText: "取消",
        confirmText: "确定",
        format: "YYYY-MM-DD",
        startDate: "",
        onConfirm(value) {
          if (!index) {
            _this.search.startTime = value;
          } else {
            _this.search.endTime = value;
          }
        },
        onHide(type) {
          if (type === "cancel") {
            // that.banci = value
          }
        }
      });
    },
    changeWidgetIndex(index) {
      this.chartActive = index;
      let startTime, endTime;
      if (index === 0) {
        startTime = dayjs().subtract(6, "hour");
        endTime = dayjs();
      } else if (index === 1) {
        startTime = dayjs().startOf("date");
        endTime = dayjs()
          .startOf("date")
          .add(1, "day");
      } else if (index === 2) {
        startTime = dayjs().startOf("month");
        endTime = dayjs()
          .startOf("month")
          .add(1, "month");
      } else if (index === 3) {
        startTime = dayjs().startOf("year");
        endTime = dayjs()
          .startOf("year")
          .add(1, "year");
      }
      let date = {
        startTime,
        endTime
      };
      this.getChartDataDetail(date);
    },
    //展开更多
    changeMore() {
      this.showMore = !this.showMore;
    },
    getChartDataDetail(date) {
      // 1:小时 2:日，周 3:月 4:年
      let params = {
        cycleType: this.chartActive,
        deviceCode: "",
        endTime: date.endTime,
        energyType: this.type,
        startTime: date.startTime
      };
      EnergyConsumeDao.getEnergyConsumeChartData(params, res => {
        this.chartData.splice(0);
        if (res && res.length) {
          res.sort((a, b) => a.dataTime - b.dataTime);
          this.chartData = res;
        }
        this.setChart();
      });
    },
    setChart() {
      if (!this.chart) {
        let option = {
          color: ["#F94B48", "#F9D64A", "#54CA75", "#456DE5"],
          grid: {
            containLabel: true,
            top: "18%",
            bottom: "10%",
            left: "4%",
            right: "4%"
          },
          tooltip: {
            trigger: "axis",
            axisPointer: {
              type: "line",
              lineStyle: {
                color: "#979797"
              }
            },
            textStyle: {
              align: "left"
            }
          },
          textStyle: {
            color: "#959595"
          },
          xAxis: {
            type: "category",
            axisLine: {
              lineStyle: {
                color: "#979797"
              }
            },
            axisTick: {
              show: false
            }
          },
          yAxis: {
            type: "value",
            axisLine: {
              show: false
            },
            axisTick: {
              show: false
            },
            splitLine: {
              lineStyle: {
                color: "#979797",
                type: "dotted"
              }
            }
          }
        };

        this.chart = this.$echarts.init(this.$refs.chart);
        this.chart.setOption(option);
      }
      let source = this.formatterDataset(this.chartData);
      let series = this.formatterSeries(this.chartData);
      // console.log(source, series);
      this.chart.setOption({
        dataset: {
          source
        },
        series
      });
      let option = this.chart.getOption();
      if (!source.length) {
        option.graphic = [
          {
            type: "text",
            left: "center",
            top: "40%",
            style: {
              text: "暂无数据",
              fill: "#fff",
              fontSize: 18
            }
          }
        ];
        this.chart.setOption(option, true);
      } else {
        option.graphic = [];
        this.chart.setOption(option, true);
      }
    },
    formatterDataset(data) {
      let dataset = [],
        xAxis = [],
        yAxis = [];

      if (data && data.length) {
        xAxis.push("时间", "用量");
        data.forEach((e, index) => {
          let date = dayjs(e.dataTime);
          if (!yAxis[index]) {
            let label = "";
            if (this.chartActive === 0) {
              label = date.format("HH:mm:ss");
            } else if (this.chartActive === 1) {
              label = date.hour() + "时";
            } else if (this.chartActive === 2) {
              label = date.date() + "日";
            } else if (this.chartActive === 3) {
              label = date.month() + 1 + "月";
            }
            yAxis.push([label, e.value]);
          } else {
            yAxis[index].push(e.value);
          }
        });
        dataset.push(xAxis, ...yAxis);
        // console.log(dataset);
        return dataset;
      } else {
        return [];
      }
    },
    formatterSeries(data) {
      let series = [{ type: "line" }];
      return series;
    },
    energyDetails(item, index) {
      this.store.pageNum = Math.ceil((index + 1) / this.pageSize);
      this.$store.commit("setEnergyDetails", item);
      this.$router.push({
        name: "energy_consume_detail",
        query: {
          type: this.type,
          id: item.id,
          deviceId: item.deviceId
        }
      });
    },
    handleDepartment(departmentDetail) {
      this.curDepartment = departmentDetail;
      this.departmentId = departmentDetail.id;
    },
    getDepartment(data) {
      this.department = data;
      this.curDepartment = data;
      this.departmentId = data.id;
    },
    overBtn() {
      this.showMore = false;
      this.store.pageNum = 0;
      this.getEnergyConsumeMore();
    },
    change(id, departmentName) {
      this.curDepartment = {
        departmentName,
        id: id
      };
    },
    showTreeFn(status) {
      if (status) {
        this.$refs.selece_icon.$el.style.transform = "rotate(-180deg)";
      } else {
        this.$refs.selece_icon.$el.style.transform = "rotate(0deg)";
      }
      this.showTree = status;
    },
    // updateCache(id, name) {
    //   this.curDepartment = {
    //     name: name,
    //     id: id
    //   };
    // },
    reset() {
      this.curDepartment.id = "";
      this.curDepartment.departmentName = "全企业";
      this.search.deviceName = "";
      this.search.startTime = "";
      this.search.endTime = "";
    }
  }
};
</script>
<style lang="less">
.energy-tab {
  .vux-tab {
    height: 45px !important;
    background: #1b1c32;
    .vux-tab-item {
      background: none;
      color: #fff;
    }
  }
}
</style>
<style lang="less" scoped>
.report_time {
  font-size: 12px;
  color: #ffffff59;
}
.fade-enter-active,
.fade-leave-active {
  transform: translateY(0);
}
.fade-enter, .fade-leave-to /* .fade-leave-active below version 2.1.8 */ {
  transform: translateY(-140%);
}
.energy {
  height: 100vh;
  background: #1b1c32;
  &.show-more-open {
    overflow: hidden;
  }
  .energy-work {
    background: #1b1c32;
    .energy-work-wrapper {
      padding: 16px 8px 32px;
      // height: calc(~"100vh" - 138px);
      overflow: auto;
      .energy-card {
        margin-bottom: 12px;
        .energy-card-body {
          display: flex;
          flex-wrap: wrap;
          .body-item {
            flex: none;
            font-size: 14px;
            margin: 3px 0;
            width: 65%;
            &:nth-child(2n) {
              width: 35%;
            }
            .body-item-key {
              color: gray;
            }
            .body-item-value {
              &.warning {
                color: #ff2c2c;
              }
            }
          }
        }
      }
      .newpage_work_more {
        height: 40px;
        font-size: 12px;
        line-height: 40px;
        text-align: center;
        color: #456de6;
      }
    }
  }

  .chart-box {
    padding: 10px;

    background: #23233d;
    color: #fff;
    text-align: center;
    font-size: 12px;
    position: relative;
    overflow: hidden;
    &:first-child {
      margin-left: 0;
    }
    &:last-child {
      margin-right: 0;
    }
    &.card-box {
      height: 64px;
      padding: 10px 2px;
      box-sizing: border-box;
      flex: 1;
      overflow: hidden;
      cursor: default;
      .num,
      .name {
        width: 100%;
        line-height: 18px;
        overflow: hidden;
        white-space: nowrap;
        text-overflow: ellipsis;
      }
      .num {
        line-height: 26px;
        font-size: 20px;
      }
      .edit {
        line-height: 18px;
        padding: 5px 0;
        color: #1d4fa0;
      }
      &.active {
        color: #fff;
        background-color: #456de6;
      }
    }
    .chart-title {
      font-size: 14px;
      text-align: left;
      display: flex;
      justify-content: space-between;
      align-items: center;
    }
    .group-list {
      font-size: 14px;
      display: flex;
      justify-content: center;
      border: 1px solid #456de6;
      border-radius: 2px;
      .list-item {
        padding: 0 20px;
        text-align: center;
        color: #456de6;
        flex: 1;
        white-space: nowrap;
        &.active {
          color: #fff;
          background-color: #456de6;
        }
      }
    }
    .chart-area {
      height: 240px;
      margin: 4px 0;
      background-color: #292a4d;
    }
  }
  .MoreDataP {
    position: fixed;
    z-index: 1000;
    top: 0;
    right: 0;
    left: 0;
    bottom: 0;
    transition: transform 0.3s ease-in-out;
    // transform: translateY(-120%);
    background: #22233f;
    input {
      &::placeholder {
        color: gray !important;
      }
    }
    .nav-center {
      font-size: 16px;
      color: #fff;
      line-height: 44px;
      text-align: center;
    }
    .MoreDataPInner {
      width: 100%;
      color: #ffffff;
      background: #22233f;
    }
    // &.show {
    //   transform: translateY(0);
    // }
    // &.hide {
    //   transform: translateY(-120%);
    // }
    .searchItem {
      padding: 0 16px 16px;
      // &.addP {
      //   padding-bottom: calc(~"100vh - 400px") !important;
      // }
      .curSelectItem {
        .department_box {
          display: flex;
          justify-content: space-between;
          align-items: center;
          position: relative;
          .department_select {
            position: relative;
            width: 100%;
            border-radius: 2px;
            background: #292a4d;
            transition: background 0.3s ease-in-out;

            &.active {
              background: #383a69;
            }
            .department_name {
              padding: 5px 9px;
              padding-right: 30px;
              color: #fff;
              font-size: 16px;
              overflow: hidden;
              text-overflow: ellipsis;
              white-space: nowrap;
            }
            .selece_icon {
              position: absolute;
              top: 50%;
              right: 8px;
              margin-top: -6px;
              transition: transform 0.3s ease-in-out;
              transform-origin: 50% 50%;
            }
          }
          .dep_box {
            position: absolute;
            left: 16px;
            right: 16px;
            bottom: -255px;
            padding-right: 16px;
            color: #000;
            background: rgba(255, 255, 255, 0.9);
            border-radius: 4px;
            height: 250px;
            overflow-y: scroll;
            z-index: 9999999;
            -webkit-overflow-scrolling: touch;
          }
        }
      }
      .title {
        font-size: 16px;
        margin: 8px 0;
      }
      .inner {
        input[type="text"] {
          height: 30px;
          line-height: 30px;
          font-size: 16px;
          background: #292a4d;
          width: 100%;
          margin-bottom: 12px;
          color: #fff;
          padding: 0 8px;
          transition: background 0.3s ease-in-out;
          &:focus {
            background: #383a69;
          }
          &::placeholder {
            line-height: 30px;
          }
        }

        .time {
          display: flex;
          align-items: center;
          font-size: 16px;
          padding: 0 4px 4px;
          background: #292a4d;
          .time-text {
            width: 20px;
            padding: 0 3px;
            text-align: center;
          }
          .time-span {
            flex: 1;
            padding: 2px 0;
            text-align: center;
            border-bottom: 1px solid #dedede;
          }
        }
      }
    }

    .BtnGroup {
      display: flex;
      width: 100%;
      height: 44px !important;
      line-height: 44px !important;
      transition: 0.3s all;
      padding-top: 32px;
      background: #22233f;
      div {
        text-align: center;
        height: 44px !important;
        border-top: 1px #3967dc solid;
        border-bottom: 1px #3967dc solid;
      }
    }
    .btn-reset {
      flex: 1;
      background: #22233f;
      padding: 0 15px;
      border-radius: 0;
      color: #456de6;
      line-height: 44px !important;
      transition: 0.3s all;
      &.active {
        background: #456de6;
        color: #fff;
      }
    }
    .btn-over {
      flex: 2;
      background: #3967dc;
      padding: 0 15px;
      color: #fff;
      border-radius: 0;
      line-height: 44px !important;
      transition: 0.3s all;
      &.active {
        background: #6e92ff;
      }
    }
  }
}
.none_conent {
  text-align: center;
  color: gray;
  /* height:30px;
    line-height:30px; */
  border-bottom: none !important;
}

.not-content {
  width: 100%;
  display: flex;
  justify-content: center;
  align-items: center;
  flex-direction: column;
  text-align: center;
  img {
    width: 64px;
    height: 64px;
    margin-left: 20px;
  }
  .title {
    margin: 8px auto;
    width: 126px;
    height: 40px;
    font-size: 14px;
    font-family: PingFangSC-Regular, PingFang SC;
    font-weight: 400;
    color: rgba(158, 198, 251, 1);
    line-height: 20px;
    text-align: center;
  }
}
.energy-title {
  height: 44px;
  background: #18182c;
  padding: 0 15px;
  display: flex;
  justify-content: space-between;
  position: relative;
  span {
    display: inline-block;
    color: #ffff;
    font-size: 15px;
    vertical-align: middle;
  }
  .nav-left {
    display: flex;
    align-items: center;
    .company-logo {
      height: 100%;
      width: 48px;
    }
    .title {
      color: #fff;
      font-size: 16px;
    }
  }
  .nav-center {
    line-height: 44px;
    position: absolute;
    left: 0;
    right: 0;
    text-align: center;
  }
  .nav-border-left {
    border-left: 2px solid #fff;
    height: 16px;
  }
  .nav-right {
    position: relative;
    // width: 30px;
    height: 100%;
    display: flex;
    justify-content: space-between;
    align-items: center;
    .paidan {
      margin-top: -8px;
      i {
        font-size: 26px;
      }
    }
  }
}
</style>
